package oop.ex3.nameserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Represents a working NameServer.
 * 
 * @author zablo
 *
 */
public class MyNameServer {
	private static final int PORT_ARG_INDEX=0,TIMEOUT_5_SECONDS=5000;
	
	/**
	 * Handles the run of the nameServer.
	 * @param args assuming input is valid, args[0] contains the NS's port.
	 */
	public static void main(String[] args){
		// Initiates the nameServer
		NameServer server=new NameServer(Integer.parseInt(args[PORT_ARG_INDEX]));
		ServerSocket serverSocket;
		ExecutorService sessions = Executors.newCachedThreadPool();
		
			serverSocket=server.getServerSocket();
			Socket clientSocket;
			
			while (!serverSocket.isClosed()){
				
				try{
				
					clientSocket=serverSocket.accept();
					clientSocket.setSoTimeout(TIMEOUT_5_SECONDS);
					sessions.execute(new SessionThread(clientSocket, server));
				}catch (SocketTimeoutException e1){
					//timeout, restarting serverSocket.
					server.restartServerSocket();
					System.out.println("ServerSocket Timed Out...");
				}catch (IOException e2){
					System.out.println("Server has been Shut-Down...");
					//serverSocket cannot accept a new connection - it's closed
					break;
				}
			}	
			
			sessions.shutdown();
			while (!sessions.isTerminated()){	
			}
			
			return;
					
	}
}
